package com.zhijiaoyun.task;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author shisfish
 * @date 2018/1/23
 */
public class WebsocketEndPoint extends TextWebSocketHandler {

	private final static Log log = LogFactory.getLog(WebsocketEndPoint.class);

	private static final ArrayList<WebSocketSession> USERS;
	static {
		USERS = new ArrayList<>();
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		log.debug("connect to the websocket success......");
		USERS.add(session);
		// String userName = (String)
		// session.getAttributes().get(DsConstant.WEBSOCKET_USERNAME);
		// if(userName!= null){
		// //查询未读消息
		// int count = webSocketService.getUnReadNews((String)
		// session.getAttributes().get(DsConstant.WEBSOCKET_USERNAME));
		//
		// session.sendMessage(new TextMessage(count + ""));
		// }

		// testPlay();
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		if (session.isOpen()) {
			session.close();
		}
		log.debug("websocket connection closed......");
		USERS.remove(session);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		log.debug("websocket connection closed......");
		USERS.remove(session);
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

		super.handleTextMessage(session, message);
		log.debug("GOMA === > WebSocketEndPoint.handlerTextMessage...");

		System.out.println("websocket收到信息-------------");
		System.out.println(message.getPayload());

		// GameService gameService = (GameService)
		// SpringContextsUtil.getBean("gameService");

		// 微信端请求游戏加入信息
		if ("1".equals(message.getPayload())) {
			// long joins = gameService.getGameJoins(null);
			// String timeString = gameService.getPlayGame().waitString;
			// if (timeString == null || timeString.length() == 0) {
			// long time = gameService.getPlayGame().getPlayTime().getTime() -
			// new Date().getTime();
			// timeString = time/(60 * 1000) + "分钟";
			// }
			//
			// String msg = "{\"type\":1,\"count\":\"" + joins +"\",\"time\":\""
			// +timeString + "\"}";
			session.sendMessage(new TextMessage("df"));
		} else {

			// Gson gson = new Gson();
			// PointClass pointClass = gson.fromJson(message.getPayload(),
			// PointClass.class);
			// if (pointClass != null && "point".equals(pointClass.type)) {
			// //小游戏加点
			// GameJoin info =
			// gameService.getGameJoinByUserId(pointClass.user_id);
			// info.setShake_num(pointClass.point);
			// gameService.updateGameJoin(info);
			// }
		}
	}

	/**
	 * 给所有在线用户发送消息
	 *
	 * @param message
	 */
	public void sendMessageToUsers(TextMessage message) {

		System.out.println("websocket发送信息-------------");
		System.out.println(message.getPayload());

		for (WebSocketSession user : USERS) {
			try {
				if (user.isOpen()) {
					user.sendMessage(message);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 测试
	 */
	public void testPlay() {

		try {
			Thread.sleep(10000);
		} catch (InterruptedException ie) {
		}
		String msg = "{\"type\":2,\"sysTime\":\"2016-10-19 13:46:00\",\"startTime\":\"2016-10-19 13:46:06\"}";
		sendMessageToUsers(new TextMessage(msg));
	}

	public class PointClass {
		private String type;
		private long user_id;
		private int point;

		public String getType() {
			return type;
		}

		public void setType(String type) {
			this.type = type;
		}

		public long getUser_id() {
			return user_id;
		}

		public void setUser_id(long user_id) {
			this.user_id = user_id;
		}

		public int getPoint() {
			return point;
		}

		public void setPoint(int point) {
			this.point = point;
		}

	}
}
